<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/13
 * Time: 16:45
 */

namespace app\controllers;

use app\models\Customer;
use app\models\CustomerRefer;
use yii;
use app\service\OrderService;
use app\lib\BaseFunction;
use app\models\{
    Invoice, Baoxiao, Income, OrderModel, Staff, Product, Invoice_new, Bank_bill, Repo,
    PrintModel, Inland, Express, Purchase
};

class OrderController extends ApiBaseController
{
    /**
     * invoice订单
     */
    public function actionInvoiceList()
    {
        $p = is_numeric(yii::$app->request->get('p')) ? yii::$app->request->get('p') : 1;
        $s = is_numeric(yii::$app->request->get('s')) ? yii::$app->request->get('s') : 50;
        $where['job_number'] = yii::$app->request->get('job_number');
        $where['customer_name'] = trim(yii::$app->request->get('customer_name', ''));
        $where['invoice'] = trim(yii::$app->request->get('invoice', ''));
        $where['begin_date'] = yii::$app->request->get('begin_date');
        $where['end_date'] = yii::$app->request->get('end_date');
        $where['confirm_begin_date'] = yii::$app->request->get('confirm_begin_date');
        $where['confirm_end_date'] = yii::$app->request->get('confirm_end_date');
        $where['invoice_status'] = yii::$app->request->get('invoice_status');
        $where['order_status'] = yii::$app->request->get('order_status');
        $where['purchase'] = yii::$app->request->get('purchase');
        $where['recommend'] = yii::$app->request->get('recommend');
        $where['is_jiesuan'] = yii::$app->request->get('is_jiesuan');
        $db = new Invoice();

        //业务员查看
        if ($this->user['role'] == 3) {
            $where['job_number'] = $this->user['job_number'];
        } elseif ($this->user['role'] == 4) {
            $where['purchase'] = $this->user['job_number'];
        }
        $list = $db->get_invoice_all_info($p, $s, $where);
        $size = $db->get_invoice_new_size($where);
        $size = $size ? $size['num'] : 0;
        $totalOrderPay = 0;
        $totalIncome = 0;
        $totalPay = 0;
        $totalFee = 0;
        $totalShip = 0;
        $totalPrint = 0;
        $totalRepo = 0;
        $totalBank = 0;
        $totalInland = 0;
        $totalOthers = 0;
        $totalProfit = 0;
        $totalSaleman = 0;
        $totalPurchase = 0;
        //给invoice添加收入
        $invoice_arr = [];
        foreach ($list['list'] as $k => $v) {
            $invoice_arr[] = $v['invoice'];
            foreach ($list['income'] as $k2 => $v2) {
                if (trim($v['invoice']) == trim($v2['invocie_num'])) {
                    $totalOrderPay += $v['order_pay'];
                    $totalIncome += $v2['in_come'];
                    $totalPay += $v2['total_fee'];
                    $totalFee += $v2['fee'];
                    $list['list'][$k]['income'] = $v2;
                    $list['list'][$k]['date2'] = $v2['date'];
                    unset($list['income'][$k2]);
                    break;
                }
            }
        }
        unset($list['income']);
        //invoice添加运费
        $express_model = new \app\models\Express();
        $express_list = $express_model->get_all_express_money($invoice_arr);

        //invoice添加仓库费用
        $repo_model = new \app\models\Repo();
        $repofee_list = $repo_model->get_repo_fee_by_invoice($invoice_arr);


        //打印费用添加
        $print_model = new \app\models\PrintModel();
        $print_list = $print_model->get_print_fee_by_invoice($invoice_arr);


        //大货报销支出
        $bank_bill = new \app\models\Bank_bill();
        $bank_list = $bank_bill->get_money_by_invoice($invoice_arr);

        $othersList = $bank_bill->get_others_by_invoice($invoice_arr);

        //添加汇率
        $commonModel = new \app\models\CommonModel();
        $exchange_list = json_decode($commonModel->get_all_exchange_rate(), true);

        //内陆费用添加
        $inlandModel = new \app\models\Inland();
        $inland_list = $inlandModel->get_inland_list_by_invoice($invoice_arr);

        //报销费用添加
        $baoxiaoModel = new Baoxiao();
        $baoxiaoList = $baoxiaoModel->getBaoxiaoByInvoice($invoice_arr);
        foreach ($list['list'] as $k => $v) {
            $list['list'][$k]['express_fee'] = 0;
            foreach ($express_list as $v2) {
                if ($v['invoice'] == $v2['invoice_order']) {
                    if ($v['customer_num'] != $v2['customer_number']) {
                        $list['list'][$k]['isSame'] = false;
                    }
                    $list['list'][$k]['express_fee'] += $v2['fee'];
                    $totalShip += $v2['fee'];
                }
            }

            $list['list'][$k]['repo_fee'] = 0;
            foreach ($repofee_list as $v2) {
                if ($v['invoice'] == $v2['invoice_order']) {
                    if ($v['customer_num'] != $v2['num']) {
                        $list['list'][$k]['isSame'] = false;
                    }
                    $list['list'][$k]['repo_fee'] = $v2['pay_all'];
                    $totalRepo += $v2['pay_all'];
                    break;
                }
            }

            $list['list'][$k]['print_fee'] = 0;
            foreach ($print_list as $v2) {
                if ($v['invoice'] == $v2['invoice_order']) {
                    $list['list'][$k]['print_fee'] = $v2['fee'];
                    $totalPrint += $v2['fee'];
                    break;
                }
            }

            $list['list'][$k]['bank'] = 0;
            foreach ($bank_list as $v2) {
                if ($v['invoice'] == $v2['invocie_num']) {
                    if ($v['customer_num'] != $v2['number']) {
                        $list['list'][$k]['isSame'] = false;
                    }
                    $list['list'][$k]['bank'] = $v2['in_money'] - $v2['out_money'];
                    $totalBank += $v2['in_money'] - $v2['out_money'];
                    break;
                }
            }

            $list['list'][$k]['others'] = 0;
            foreach ($othersList as $v2) {
                if ($v['invoice'] == $v2['invocie_num']) {
                    $list['list'][$k]['others'] = $v2['in_money'] - $v2['out_money'];
                    $totalOthers += $v2['in_money'] - $v2['out_money'];
                    break;
                }
            }

            $list['list'][$k]['exchange_rate'] = 6.5;
            foreach ($exchange_list as $v2) {
                $date = isset($v['date2']) ? $v['date2'] : $v['date'];
                if (date('Ym', strtotime($date)) == $v2['month']) {
                    $list['list'][$k]['exchange_rate'] = $v2['rate'];
                    break;
                }
            }

            $list['list'][$k]['inland_fee'] = 0;
            foreach ($inland_list as $v2) {
                if ($v['invoice'] == $v2['invoice']) {
                    if ($v['customer_num'] != $v2['customer_num']) {
                        $list['list'][$k]['isSame'] = false;
                    }
                    $list['list'][$k]['inland_fee'] = $v2['total_fee'];
                    $totalInland += $v2['total_fee'];
                    break;
                }
            }
            $list['list'][$k]['baoxiao'] = isset($baoxiaoList[$v['invoice']]) ? $baoxiaoList[$v['invoice']] : 0;

        }

        $model = new \app\models\Staff();
        $staff_list = $model->get_all_saleman();
        foreach ($list['list'] as $k => $v) {
            if (isset($v['income'])) {
                $clean = $v['income']['in_come'] + $v['income']['total_fee'] + $v['income']['fee'];
            } else {
                $clean = 0;
            }
            $list['list'][$k]['clean'] = $clean;
            $lirun = $clean > 0 ? round(($clean * $v['exchange_rate'] + $v['bank'] + $v['others'] - $v['express_fee'] - $v['print_fee'] - $v['repo_fee'] - $v['inland_fee'] - $v['baoxiao']), 2) : 0;
            $list['list'][$k]['lirun'] = $lirun;
            $totalProfit += $lirun;
            $tmp = BaseFunction::profit($v, $lirun, $staff_list);
            $totalSaleman += $tmp[0];
            $totalPurchase += $tmp[1];
            $list['list'][$k]['saleman_get'] = $tmp[0];
            $list['list'][$k]['purchase_get'] = $tmp[1];
            if ($v['rate_status'] == 1) {
                $list['list'][$k]['saleman_get'] = round($lirun * $v['rale_rate'] / 100, 2);
            }
        }
        return json_encode(['list' => $list['list'], 'total' => $size]);
    }

    public function actionInvoiceCommon()
    {
        $model = new \app\models\Staff();
        $staff = $model->get_all_saleman();
        $invoice_status = require ROOT_PATH . '/config/invoice_status.php';
        $tmp = [];
        foreach ($invoice_status as $k => $v) {
            $obj = [];
            $obj['value'] = $v;
            $obj['id'] = $k;
            $tmp[] = $obj;
        }
        $invoice_status = $tmp;
        $payStatus = yii::$app->params['pay_status'];
        $tmp = [];
        foreach ($payStatus as $k => $v) {
            $obj = [];
            $obj['value'] = $v;
            $obj['id'] = $k;
            $tmp[] = $obj;
        }
        $payStatus = $tmp;
        $orderStatus = yii::$app->params['order_status'];
        $tmp = [];
        foreach ($orderStatus as $k => $v) {
            $obj = [];
            $obj['value'] = $v;
            $obj['id'] = $k;
            $tmp[] = $obj;
        }
        $orderStatus = $tmp;
        $model = new CustomerRefer();
        $recommend = $model->list();
        return \json_encode(['recommend' => $recommend, 'staff' => $staff, 'invoice_status' => $invoice_status, 'order_status' => $orderStatus, 'pay_status' => $payStatus]);
    }

    public function actionInvoiceDetail()
    {
        if (!yii::$app->request->isPost) {
            return json_encode(['code' => 0, 'msg' => 'not allowed']);
        }
        $in = yii::$app->request->post('invoice');
        if (!$in) {
            return false;
        }
        //invoice 产品添加
        $model = new Product();
        $product_list = $model->get_invoice_product($in);
        //计算产品利润
        foreach ($product_list as $k => $v) {
            $total = $v['price_rmb'] * $v['number'] + $v['extra_fee'];
            $dollar_total = $v['price_dollar'] * $v['number'] + $v['customer_extra_fee'];
            $product_list[$k]['total'] = $total;
            $product_list[$k]['dollar_total'] = $dollar_total;
        }
        $model = new Invoice_new();
        $detail = $model->getDetailByInvoice($in);
        //获取in所有产品
        $model = new Bank_bill();
        $list = $model->get_bank_info_by_in($in);
        //仓库费用添加
        $repo_model = new Repo();
        $repo_info = $repo_model->get_repo_info_by_invoice($in);
        //印刷费添加
        $print_model = new PrintModel();
        $print_info = $print_model->get_print_list_by_invoice($in);
        //内陆费
        $inland_model = new Inland();
        $inland_info = $inland_model->get_inland_list_by_invoice((array)$in);

        $invoice_model = new Invoice_new();
        $info = $invoice_model->get_invoice_info_by_invoice($in);


        //invoice 收入$添加
        $model = new Income();
        $income_list = $model->get_income_by_invoice($in);

        $express_model = new Express();
        $express_list = $express_model->get_all_express_money($in);

        $expressType = $express_model->get_express_type();
        foreach ($express_list as $k => $v) {
            foreach ($expressType as $v2) {
                if ($v['express_id'] == $v2['id']) {
                    $express_list[$k]['name'] = $v2['name'];
                }
            }
        }
        //读取采购单合同信息
        $purchase = new Purchase();
        $purchase_list = $purchase->all(['invoice' => $in]);
        $arr = [];
        foreach ($purchase_list as $v) {
            $tmp = json_decode($v['product_list'], true);
            foreach ($tmp as $v2) {
                array_push($arr, $v2);
            }
        }
        $invoiceModel = new Invoice_new();
        $detail = $invoiceModel->one(['invoice' => $in]);
        $data = [];
        $data['express'] = $express_list;
        $data['repo'] = $repo_info;
        $data['print'] = $print_info;
        $data['inland'] = $inland_info;
        $data['list'] = $list;
        $data['product'] = $product_list;
        $data['detail'] = $detail;
        $data['income'] = $income_list;
        return \json_encode($data);
    }

    /**生成订单
     * @return string
     */
    public function actionGenerateSampleOrder()
    {
        if (!yii::$app->request->isPost) {
            return \json_encode(['code' => 0, 'msg' => 'method not allowed']);
        }
        $totalMoney = trim(yii::$app->request->post('total_money', ''));
        $customerNum = trim(yii::$app->request->post('number', ''));
        $quote = trim(yii::$app->request->post('quote_id', ''));
        $remark = yii::$app->request->post('remark');
        $name = yii::$app->request->post('name');
        $item = yii::$app->request->post('items');
        $model = new Customer();
        $info = $model->one('id', ['number' => $customerNum]);
        if (!$info) {
            return \json_encode(['code' => 0, 'msg' => '客户编号不存在']);
        }
        $service = new OrderService();
        $order_num = $service->generateOrderNum(1, 1, $info['id']);
        $data = [];
        $data['order_num'] = $order_num;
        $data['create_at'] = time();
        $data['type'] = 1;
        $data['total_money'] = $totalMoney;
        $data['user_id'] = $info['id'];
        $data['link_id'] = $quote;
        $data['name'] = $name;
        $data['items'] = $item;
        $data['remark'] = $remark;
        $data['staff'] = $this->currentUser()['job_number'];
        $re = $service->insertRecord($data);
        if ($re) {
            return \json_encode(['code' => 1, 'msg' => '订单生成成功']);
        } else {
            return \json_encode(['code' => 0, 'msg' => '订单生成失败,请重试']);
        }
    }

    public function actionCancelSample()
    {
        if (!yii::$app->request->isPost) {
            return json_encode(['code' => 0, 'msg' => 'not allowed']);
        }
        $id = yii::$app->request->post('id');
        //检查是否已经付款
        $model = new OrderModel();
        $res = $model->one(['id' => $id]);
        if ($res) {
            if ((int)$res['have_pay'] == 2) {
                return json_encode(['code' => 0, 'msg' => '订单已经支付成功']);
            }
            //更新
            $re = $model->save(['have_pay' => 3], ['id' => $id]);
            if ($re) {
                return \json_encode(['code' => 1, 'msg' => '取消成功']);
            } else {
                return \json_encode(['code' => 0, 'msg' => '取消失败，请重试']);
            }
        }
    }

    /**收款数据汇总
     * @return string
     */
    public function actionSellChartData()
    {
        $year = yii::$app->request->get('year') ?? '2018';
        $totalArr = [];
        $db = new Income();
        $list = $db->sell_performance($year);
        $model = new Staff();
        $staff = $model->get_all_saleman();
        if ($this->user['role'] != 1 && $this->user['role'] != 2) {
            foreach ($list as $k => $v) {
                if ($k != $this->user['job_number']) {
                    unset($list[$k]);
                }
            }
        }
        foreach ($list as $k => $v) {
            foreach ($staff as $v2) {
                if ($v['service_name'] == $v2['job_number']) {
                    $list[$k]['name'] = $v2['name'];
                }
            }
        }

        $arr = [];
        foreach ($list as $v) {
            if (isset($totalArr[$v['MONTH']])) {
                $totalArr[$v['MONTH']]['total'] += $v['money'];
            } else {
                $totalArr[$v['MONTH']]['total'] = $v['money'];
            }

            $arr[$v['name']][$v['MONTH']][$v['pay_from']] = $v['money'];
        }
        foreach ($arr as $k => $v) {
            $total = 0;
            foreach ($v as $k2 => $v2) {
                $monthTotal = 0;
                foreach ($v2 as $v3) {
                    $monthTotal += $v3;
                    $total += $v3;
                }
                $arr[$k][$k2]['total'] = $monthTotal;
            }
            $arr[$k]['total'] = $total;
        }
        $arr['total'] = $totalArr;
        echo \json_encode(['list' => $arr, 'year' => $year]);
        exit;

    }

    public function actionUpdate()
    {
        $post = yii::$app->request->post();
        foreach ($post as $k => $v) {
            if (!in_array($k, ['id', 'value', 'column'])) {
                return json_encode(['code' => 0, 'msg' => '参数错误']);
            }
        }
    }

    /**更新订单详情
     * @return string
     */
    public function actionUpdateOrderDetail()
    {

        if (yii::$app->request->isPost) {
            $id = yii::$app->request->post('id');
            $column = yii::$app->request->post('column');
            $value = yii::$app->request->post('value');
            $table = yii::$app->db->tablePrefix . 'product';
            $sql = 'SELECT is_jiesuan from jingsourcing_invoice_new a 
                    LEFT JOIN jingsourcing_product as b ON a.invoice=b.invoice
                    WHERE b.id = :id';
            $re = yii::$app->db->createCommand($sql, ['id' => $id])->queryOne();
            if ($re) {
                if ((int)$re['is_jiesuan'] == 3) {
                    return json_encode(['code' => 0, 'msg' => '订单已结算']);
                }
            }
            $re = yii::$app->db->createCommand()->update($table, [$column => $value], ['id' => $id])->execute();
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '更新成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '更新失败，请重试']);
            }
        }

    }
}